function Promise(executor) {
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];
    const resolve = (value) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.success();
            })
        }
    }
    const reject = (reason) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.fail();
            })
        }
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}
Promise.prototype.then = function (onResolve, onReject) {
    if(typeof onReject !== 'function'){
        // 失败回调默认值：失败回调有一个基本要求，将promise失败的状态和结果值向下传递
        onReject = reason=>new Promise((resolve,reject)=>reject(reason));
    }
    if(typeof onResolve !== 'function'){
        // 成功回调默认值：成功回调有一个基本要求，将promise成功的状态和结果值向下传递
        onResolve = value=>value;
    }
    return new Promise((resolve, reject) => {
        const changeState = (fn) => {
            // 捕获then方法成功或失败回调函数中抛出的异常
            try{
                let rs = fn(this.PromiseResult);
                if (rs instanceof Promise) {// rs 是Promise
                    rs.then(resolve, reject)
                } else {// rs不是Promise
                    resolve(rs);
                }
            }catch(e) {
                reject(e)
            }
        }
        if (this.PromiseState === 'fulfilled') {
            changeState(onResolve)
        }
        if (this.PromiseState === 'rejected') {
            changeState(onReject)
        }
        if (this.PromiseState === 'pending') {
            this.callbacks.push({
                success: () => {
                    changeState(onResolve)
                },
                fail: () => {
                    changeState(onReject)
                }
            })
        }
    })
}